package com.example.tests;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import com.example.data.GroupData;

public class GroupDataGenerator {

	public static void main(String[] args) throws IOException {
		if (args.length != 2) {
			System.out.println("Please specify parametres: <amount of test data> <file>");
			return;
		}
		
		int amount = Integer.parseInt(args[0]);
		File file = new File(args[1]);		
		
		if (file.exists()){
			System.out.println("File exists, please remote it manually: " + file);
			return;
		}		
		saveGroupsToCsvFile(generateRandomGroups(amount), file);				
	}

	private static void saveGroupsToCsvFile(List<GroupData> groups, File file) throws IOException {		
			FileWriter writer= new FileWriter(file);
			for (GroupData group : groups) {
				writer.write(group.getName() + "," + group.getHeader() + "," + group.getFooter() + ",!\n");
			}
			writer.close();
	}
	
	public static List<GroupData> loadGropsFromCsvFile(File file) throws IOException {
		 List<GroupData> list = new ArrayList<GroupData>();
		 FileReader reader = new FileReader(file);
		 BufferedReader bufferedReader = new BufferedReader(reader);		 		 
		 String line = bufferedReader.readLine();
		 while(line != null){
			 String[] parts = line.split(",");
			 GroupData group = new GroupData()
			  .withName(parts[0])
			  .withHeader(parts[1])
			  .withFooter(parts[2]);
			 list.add(group);
			 line = bufferedReader.readLine();
		 }
		 bufferedReader.close();
		 return list;
	}

	
	public static List<GroupData> generateRandomGroups(int amount) {
		 List<GroupData> list = new ArrayList<GroupData>();
		  for (int i = 0; i < amount; i++){
			   GroupData group = new GroupData()
			   	.withName(generateRandomString())
			   	.withHeader(generateRandomString())
			   	.withFooter(generateRandomString());			   			  
			   list.add(group);
		  }
		  return list;
	}
	
	private static String generateRandomString(){
		  Random rnd = new Random();
		  if (rnd.nextInt(3) == 0) {
			   return "";
		   } else {
			   return "test" + rnd.nextInt();
		   }
	}	

}
